{
 "nbformat_minor": 1, 
 "nbformat": 4, 
 "cells": [
  {
   "source": [
    "# Generative Adversarial Networks (GANs)\n", 
    "\n", 
    "So far in CS231N, all the applications of neural networks that we have explored have been **discriminative models** that take an input and are trained to produce a labeled output. This has ranged from straightforward classification of image categories to sentence generation (which was still phrased as a classification problem, our labels were in vocabulary space and we\u2019d learned a recurrence to capture multi-word labels). In this notebook, we will expand our repetoire, and build **generative models** using neural networks. Specifically, we will learn how to build models which generate novel images that resemble a set of training images.\n", 
    "\n", 
    "### What is a GAN?\n", 
    "\n", 
    "In 2014, [Goodfellow et al.](https://arxiv.org/abs/1406.2661) presented a method for training generative models called Generative Adversarial Networks (GANs for short). In a GAN, we build two different neural networks. Our first network is a traditional classification network, called the **discriminator**. We will train the discriminator to take images, and classify them as being real (belonging to the training set) or fake (not present in the training set). Our other network, called the **generator**, will take random noise as input and transform it using a neural network to produce images. The goal of the generator is to fool the discriminator into thinking the images it produced are real.\n", 
    "\n", 
    "We can think of this back and forth process of the generator ($G$) trying to fool the discriminator ($D$), and the discriminator trying to correctly classify real vs. fake as a minimax game:\n", 
    "$$\\underset{G}{\\text{minimize}}\\; \\underset{D}{\\text{maximize}}\\; \\mathbb{E}_{x \\sim p_\\text{data}}\\left[\\log D(x)\\right] + \\mathbb{E}_{z \\sim p(z)}\\left[\\log \\left(1-D(G(z))\\right)\\right]$$\n", 
    "where $x \\sim p_\\text{data}$ are samples from the input data, $z \\sim p(z)$ are the random noise samples, $G(z)$ are the generated images using the neural network generator $G$, and $D$ is the output of the discriminator, specifying the probability of an input being real. In [Goodfellow et al.](https://arxiv.org/abs/1406.2661), they analyze this minimax game and show how it relates to minimizing the Jensen-Shannon divergence between the training data distribution and the generated samples from $G$.\n", 
    "\n", 
    "To optimize this minimax game, we will aternate between taking gradient *descent* steps on the objective for $G$, and gradient *ascent* steps on the objective for $D$:\n", 
    "1. update the **generator** ($G$) to minimize the probability of the __discriminator making the correct choice__. \n", 
    "2. update the **discriminator** ($D$) to maximize the probability of the __discriminator making the correct choice__.\n", 
    "\n", 
    "While these updates are useful for analysis, they do not perform well in practice. Instead, we will use a different objective when we update the generator: maximize the probability of the **discriminator making the incorrect choice**. This small change helps to allevaiate problems with the generator gradient vanishing when the discriminator is confident. This is the standard update used in most GAN papers, and was used in the original paper from [Goodfellow et al.](https://arxiv.org/abs/1406.2661). \n", 
    "\n", 
    "In this assignment, we will alternate the following updates:\n", 
    "1. Update the generator ($G$) to maximize the probability of the discriminator making the incorrect choice on generated data:\n", 
    "$$\\underset{G}{\\text{maximize}}\\;  \\mathbb{E}_{z \\sim p(z)}\\left[\\log D(G(z))\\right]$$\n", 
    "2. Update the discriminator ($D$), to maximize the probability of the discriminator making the correct choice on real and generated data:\n", 
    "$$\\underset{D}{\\text{maximize}}\\; \\mathbb{E}_{x \\sim p_\\text{data}}\\left[\\log D(x)\\right] + \\mathbb{E}_{z \\sim p(z)}\\left[\\log \\left(1-D(G(z))\\right)\\right]$$\n", 
    "\n", 
    "### What else is there?\n", 
    "Since 2014, GANs have exploded into a huge research area, with massive [workshops](https://sites.google.com/site/nips2016adversarial/), and [hundreds of new papers](https://github.com/hindupuravinash/the-gan-zoo). Compared to other approaches for generative models, they often produce the highest quality samples but are some of the most difficult and finicky models to train (see [this github repo](https://github.com/soumith/ganhacks) that contains a set of 17 hacks that are useful for getting models working). Improving the stabiilty and robustness of GAN training is an open research question, with new papers coming out every day! For a more recent tutorial on GANs, see [here](https://arxiv.org/abs/1701.00160). There is also some even more recent exciting work that changes the objective function to Wasserstein distance and yields much more stable results across model architectures: [WGAN](https://arxiv.org/abs/1701.07875), [WGAN-GP](https://arxiv.org/abs/1704.00028).\n", 
    "\n", 
    "\n", 
    "GANs are not the only way to train a generative model! For other approaches to generative modeling check out the [deep generative model chapter](http://www.deeplearningbook.org/contents/generative_models.html) of the Deep Learning [book](http://www.deeplearningbook.org). Another popular way of training neural networks as generative models is Variational Autoencoders (co-discovered [here](https://arxiv.org/abs/1312.6114) and [here](https://arxiv.org/abs/1401.4082)). Variational autoencoders combine neural networks with variational inference to train deep generative models. These models tend to be far more stable and easier to train but currently don't produce samples that are as pretty as GANs.\n", 
    "\n", 
    "Example pictures of what you should expect (yours might look slightly different):\n", 
    "\n", 
    "![caption](gan_outputs_tf.png)\n"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "source": [
    "## Setup"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "import tensorflow as tf\n", 
    "import numpy as np\n", 
    "import os\n", 
    "\n", 
    "import matplotlib.pyplot as plt\n", 
    "import matplotlib.gridspec as gridspec\n", 
    "\n", 
    "%matplotlib inline\n", 
    "plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\n", 
    "plt.rcParams['image.interpolation'] = 'nearest'\n", 
    "plt.rcParams['image.cmap'] = 'gray'\n", 
    "\n", 
    "# A bunch of utility functions\n", 
    "\n", 
    "def show_images(images):\n", 
    "    images = np.reshape(images, [images.shape[0], -1])  # images reshape to (batch_size, D)\n", 
    "    sqrtn = int(np.ceil(np.sqrt(images.shape[0])))\n", 
    "    sqrtimg = int(np.ceil(np.sqrt(images.shape[1])))\n", 
    "\n", 
    "    fig = plt.figure(figsize=(sqrtn, sqrtn))\n", 
    "    gs = gridspec.GridSpec(sqrtn, sqrtn)\n", 
    "    gs.update(wspace=0.05, hspace=0.05)\n", 
    "\n", 
    "    for i, img in enumerate(images):\n", 
    "        ax = plt.subplot(gs[i])\n", 
    "        plt.axis('off')\n", 
    "        ax.set_xticklabels([])\n", 
    "        ax.set_yticklabels([])\n", 
    "        ax.set_aspect('equal')\n", 
    "        plt.imshow(img.reshape([sqrtimg,sqrtimg]))\n", 
    "    return\n", 
    "\n", 
    "def preprocess_img(x):\n", 
    "    return 2 * x - 1.0\n", 
    "\n", 
    "def deprocess_img(x):\n", 
    "    return (x + 1.0) / 2.0\n", 
    "\n", 
    "def rel_error(x,y):\n", 
    "    return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))\n", 
    "\n", 
    "def count_params():\n", 
    "    \"\"\"Count the number of parameters in the current TensorFlow graph \"\"\"\n", 
    "    param_count = np.sum([np.prod(x.get_shape().as_list()) for x in tf.global_variables()])\n", 
    "    return param_count\n", 
    "\n", 
    "\n", 
    "def get_session():\n", 
    "    config = tf.ConfigProto()\n", 
    "    config.gpu_options.allow_growth = True\n", 
    "    session = tf.Session(config=config)\n", 
    "    return session\n", 
    "\n", 
    "answers = np.load('gan-checks-tf.npz')"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "source": [
    "## Dataset\n", 
    " GANs are notoriously finicky with hyperparameters, and also require many training epochs. In order to make this assignment approachable without a GPU, we will be working on the MNIST dataset, which is 60,000 training and 10,000 test images. Each picture contains a centered image of white digit on black background (0 through 9). This was one of the first datasets used to train convolutional neural networks and it is fairly easy -- a standard CNN model can easily exceed 99% accuracy. \n", 
    " \n", 
    "\n", 
    "**Heads-up**: Our MNIST wrapper returns images as vectors. That is, they're size (batch, 784). If you want to treat them as images, we have to resize them to (batch,28,28) or (batch,28,28,1). They are also type np.float32 and bounded [0,1]. "
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "class MNIST(object):\n", 
    "    def __init__(self, batch_size, shuffle=False):\n", 
    "        \"\"\"\n", 
    "        Construct an iterator object over the MNIST data\n", 
    "        \n", 
    "        Inputs:\n", 
    "        - batch_size: Integer giving number of elements per minibatch\n", 
    "        - shuffle: (optional) Boolean, whether to shuffle the data on each epoch\n", 
    "        \"\"\"\n", 
    "        train, _ = tf.keras.datasets.mnist.load_data()\n", 
    "        X, y = train\n", 
    "        X = X.astype(np.float32)/255\n", 
    "        X = X.reshape((X.shape[0], -1))\n", 
    "        self.X, self.y = X, y\n", 
    "        self.batch_size, self.shuffle = batch_size, shuffle\n", 
    "\n", 
    "    def __iter__(self):\n", 
    "        N, B = self.X.shape[0], self.batch_size\n", 
    "        idxs = np.arange(N)\n", 
    "        if self.shuffle:\n", 
    "            np.random.shuffle(idxs)\n", 
    "        return iter((self.X[i:i+B], self.y[i:i+B]) for i in range(0, N, B)) "
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# show a batch\n", 
    "mnist = MNIST(batch_size=16) \n", 
    "show_images(mnist.X[:16])"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "## LeakyReLU\n", 
    "In the cell below, you should implement a LeakyReLU. See the [class notes](http://cs231n.github.io/neural-networks-1/) (where alpha is small number) or equation (3) in [this paper](http://ai.stanford.edu/~amaas/papers/relu_hybrid_icml2013_final.pdf). LeakyReLUs keep ReLU units from dying and are often used in GAN methods (as are maxout units, however those increase model size and therefore are not used in this notebook).\n", 
    "\n", 
    "HINT: You should be able to use `tf.maximum`"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def leaky_relu(x, alpha=0.01):\n", 
    "    \"\"\"Compute the leaky ReLU activation function.\n", 
    "    \n", 
    "    Inputs:\n", 
    "    - x: TensorFlow Tensor with arbitrary shape\n", 
    "    - alpha: leak parameter for leaky ReLU\n", 
    "    \n", 
    "    Returns:\n", 
    "    TensorFlow Tensor with the same shape as x\n", 
    "    \"\"\"\n", 
    "    # TODO: implement leaky ReLU\n", 
    "    pass\n"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "source": [
    "Test your leaky ReLU implementation. You should get errors < 1e-10"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def test_leaky_relu(x, y_true):\n", 
    "    tf.reset_default_graph()\n", 
    "    with get_session() as sess:\n", 
    "        y_tf = leaky_relu(tf.constant(x))\n", 
    "        y = sess.run(y_tf)\n", 
    "        print('Maximum error: %g'%rel_error(y_true, y))\n", 
    "\n", 
    "test_leaky_relu(answers['lrelu_x'], answers['lrelu_y'])"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "## Random Noise\n", 
    "Generate a TensorFlow `Tensor` containing uniform noise from -1 to 1 with shape `[batch_size, dim]`."
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def sample_noise(batch_size, dim):\n", 
    "    \"\"\"Generate random uniform noise from -1 to 1.\n", 
    "    \n", 
    "    Inputs:\n", 
    "    - batch_size: integer giving the batch size of noise to generate\n", 
    "    - dim: integer giving the dimension of the the noise to generate\n", 
    "    \n", 
    "    Returns:\n", 
    "    TensorFlow Tensor containing uniform noise in [-1, 1] with shape [batch_size, dim]\n", 
    "    \"\"\"\n", 
    "    # TODO: sample and return noise\n", 
    "    pass\n"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "source": [
    "Make sure noise is the correct shape and type:"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def test_sample_noise():\n", 
    "    batch_size = 3\n", 
    "    dim = 4\n", 
    "    tf.reset_default_graph()\n", 
    "    with get_session() as sess:\n", 
    "        z = sample_noise(batch_size, dim)\n", 
    "        # Check z has the correct shape\n", 
    "        assert z.get_shape().as_list() == [batch_size, dim]\n", 
    "        # Make sure z is a Tensor and not a numpy array\n", 
    "        assert isinstance(z, tf.Tensor)\n", 
    "        # Check that we get different noise for different evaluations\n", 
    "        z1 = sess.run(z)\n", 
    "        z2 = sess.run(z)\n", 
    "        assert not np.array_equal(z1, z2)\n", 
    "        # Check that we get the correct range\n", 
    "        assert np.all(z1 >= -1.0) and np.all(z1 <= 1.0)\n", 
    "        print(\"All tests passed!\")\n", 
    "    \n", 
    "test_sample_noise()"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "## Discriminator\n", 
    "Our first step is to build a discriminator. You should use the layers in `tf.layers` to build the model.\n", 
    "All fully connected layers should include bias terms. For initialization, just use the default initializer used by the `tf.layers` functions.\n", 
    "\n", 
    "Architecture:\n", 
    " * Fully connected layer with input size 784 and output size 256\n", 
    " * LeakyReLU with alpha 0.01\n", 
    " * Fully connected layer with output size 256\n", 
    " * LeakyReLU with alpha 0.01\n", 
    " * Fully connected layer with output size 1 \n", 
    " \n", 
    "The output of the discriminator should thus have shape `[batch_size, 1]`, and contain real numbers corresponding to the scores that each of the `batch_size` inputs is a real image."
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def discriminator(x):\n", 
    "    \"\"\"Compute discriminator score for a batch of input images.\n", 
    "    \n", 
    "    Inputs:\n", 
    "    - x: TensorFlow Tensor of flattened input images, shape [batch_size, 784]\n", 
    "    \n", 
    "    Returns:\n", 
    "    TensorFlow Tensor with shape [batch_size, 1], containing the score \n", 
    "    for an image being real for each input image.\n", 
    "    \"\"\"\n", 
    "    with tf.variable_scope(\"discriminator\"):\n", 
    "        # TODO: implement architecture\n", 
    "        pass\n", 
    "        return logits"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "source": [
    "Test to make sure the number of parameters in the discriminator is correct:"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def test_discriminator(true_count=267009):\n", 
    "    tf.reset_default_graph()\n", 
    "    with get_session() as sess:\n", 
    "        y = discriminator(tf.ones((2, 784)))\n", 
    "        cur_count = count_params()\n", 
    "        if cur_count != true_count:\n", 
    "            print('Incorrect number of parameters in discriminator. {0} instead of {1}. Check your achitecture.'.format(cur_count,true_count))\n", 
    "        else:\n", 
    "            print('Correct number of parameters in discriminator.')\n", 
    "        \n", 
    "test_discriminator()"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "## Generator\n", 
    "Now to build a generator. You should use the layers in `tf.layers` to construct the model. All fully connected layers should include bias terms. Note that you can use the tf.nn module to access activation functions. Once again, use the default initializers for parameters.\n", 
    "\n", 
    "Architecture:\n", 
    " * Fully connected layer with inupt size tf.shape(z)[1] (the number of noise dimensions) and output size 1024\n", 
    " * `ReLU`\n", 
    " * Fully connected layer with output size 1024 \n", 
    " * `ReLU`\n", 
    " * Fully connected layer with output size 784\n", 
    " * `TanH` (To restrict every element of the output to be in the range [-1,1])"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def generator(z):\n", 
    "    \"\"\"Generate images from a random noise vector.\n", 
    "    \n", 
    "    Inputs:\n", 
    "    - z: TensorFlow Tensor of random noise with shape [batch_size, noise_dim]\n", 
    "    \n", 
    "    Returns:\n", 
    "    TensorFlow Tensor of generated images, with shape [batch_size, 784].\n", 
    "    \"\"\"\n", 
    "    with tf.variable_scope(\"generator\"):\n", 
    "        # TODO: implement architecture\n", 
    "        pass\n", 
    "        return img"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "source": [
    "Test to make sure the number of parameters in the generator is correct:"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def test_generator(true_count=1858320):\n", 
    "    tf.reset_default_graph()\n", 
    "    with get_session() as sess:\n", 
    "        y = generator(tf.ones((1, 4)))\n", 
    "        cur_count = count_params()\n", 
    "        if cur_count != true_count:\n", 
    "            print('Incorrect number of parameters in generator. {0} instead of {1}. Check your achitecture.'.format(cur_count,true_count))\n", 
    "        else:\n", 
    "            print('Correct number of parameters in generator.')\n", 
    "        \n", 
    "test_generator()"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "# GAN Loss\n", 
    "\n", 
    "Compute the generator and discriminator loss. The generator loss is:\n", 
    "$$\\ell_G  =  -\\mathbb{E}_{z \\sim p(z)}\\left[\\log D(G(z))\\right]$$\n", 
    "and the discriminator loss is:\n", 
    "$$ \\ell_D = -\\mathbb{E}_{x \\sim p_\\text{data}}\\left[\\log D(x)\\right] - \\mathbb{E}_{z \\sim p(z)}\\left[\\log \\left(1-D(G(z))\\right)\\right]$$\n", 
    "Note that these are negated from the equations presented earlier as we will be *minimizing* these losses.\n", 
    "\n", 
    "**HINTS**: Use [tf.ones_like](https://www.tensorflow.org/api_docs/python/tf/ones_like) and [tf.zeros_like](https://www.tensorflow.org/api_docs/python/tf/zeros_like) to generate labels for your discriminator. Use [tf.nn.sigmoid_cross_entropy_with_logits](https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits) to help compute your loss function. Instead of computing the expectation, we will be averaging over elements of the minibatch, so make sure to combine the loss by averaging instead of summing."
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def gan_loss(logits_real, logits_fake):\n", 
    "    \"\"\"Compute the GAN loss.\n", 
    "    \n", 
    "    Inputs:\n", 
    "    - logits_real: Tensor, shape [batch_size, 1], output of discriminator\n", 
    "        Unnormalized score that the image is real for each real image\n", 
    "    - logits_fake: Tensor, shape[batch_size, 1], output of discriminator\n", 
    "        Unnormalized score that the image is real for each fake image\n", 
    "    \n", 
    "    Returns:\n", 
    "    - D_loss: discriminator loss scalar\n", 
    "    - G_loss: generator loss scalar\n", 
    "    \n", 
    "    HINT: for the discriminator loss, you'll want to do the averaging separately for\n", 
    "    its two components, and then add them together (instead of averaging once at the very end).\n", 
    "    \"\"\"\n", 
    "    # TODO: compute D_loss and G_loss\n", 
    "    D_loss = None\n", 
    "    G_loss = None\n", 
    "    pass\n", 
    "    return D_loss, G_loss"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "source": [
    "Test your GAN loss. Make sure both the generator and discriminator loss are correct. You should see errors less than 1e-5."
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def test_gan_loss(logits_real, logits_fake, d_loss_true, g_loss_true):\n", 
    "    tf.reset_default_graph()\n", 
    "    with get_session() as sess:\n", 
    "        d_loss, g_loss = sess.run(gan_loss(tf.constant(logits_real), tf.constant(logits_fake)))\n", 
    "    print(\"Maximum error in d_loss: %g\"%rel_error(d_loss_true, d_loss))\n", 
    "    print(\"Maximum error in g_loss: %g\"%rel_error(g_loss_true, g_loss))\n", 
    "\n", 
    "test_gan_loss(answers['logits_real'], answers['logits_fake'],\n", 
    "              answers['d_loss_true'], answers['g_loss_true'])"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "# Optimizing our loss\n", 
    "Make an `AdamOptimizer` with a 1e-3 learning rate, beta1=0.5 to mininize G_loss and D_loss separately. The trick of decreasing beta was shown to be effective in helping GANs converge in the [Improved Techniques for Training GANs](https://arxiv.org/abs/1606.03498) paper. In fact, with our current hyperparameters, if you set beta1 to the Tensorflow default of 0.9, there's a good chance your discriminator loss will go to zero and the generator will fail to learn entirely. In fact, this is a common failure mode in GANs; if your D(x) learns to be too fast (e.g. loss goes near zero), your G(z) is never able to learn. Often D(x) is trained with SGD with Momentum or RMSProp instead of Adam, but here we'll use Adam for both D(x) and G(z). "
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# TODO: create an AdamOptimizer for D_solver and G_solver\n", 
    "def get_solvers(learning_rate=1e-3, beta1=0.5):\n", 
    "    \"\"\"Create solvers for GAN training.\n", 
    "    \n", 
    "    Inputs:\n", 
    "    - learning_rate: learning rate to use for both solvers\n", 
    "    - beta1: beta1 parameter for both solvers (first moment decay)\n", 
    "    \n", 
    "    Returns:\n", 
    "    - D_solver: instance of tf.train.AdamOptimizer with correct learning_rate and beta1\n", 
    "    - G_solver: instance of tf.train.AdamOptimizer with correct learning_rate and beta1\n", 
    "    \"\"\"\n", 
    "    D_solver = None\n", 
    "    G_solver = None\n", 
    "    pass\n", 
    "    return D_solver, G_solver"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "source": [
    "## Putting it all together\n", 
    "Now just a bit of Lego Construction.. Read this section over carefully to understand how we'll be composing the generator and discriminator"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "tf.reset_default_graph()\n", 
    "\n", 
    "# number of images for each batch\n", 
    "batch_size = 128\n", 
    "# our noise dimension\n", 
    "noise_dim = 96\n", 
    "\n", 
    "# placeholder for images from the training dataset\n", 
    "x = tf.placeholder(tf.float32, [None, 784])\n", 
    "# random noise fed into our generator\n", 
    "z = sample_noise(batch_size, noise_dim)\n", 
    "# generated images\n", 
    "G_sample = generator(z)\n", 
    "\n", 
    "with tf.variable_scope(\"\") as scope:\n", 
    "    #scale images to be -1 to 1\n", 
    "    logits_real = discriminator(preprocess_img(x))\n", 
    "    # Re-use discriminator weights on new inputs\n", 
    "    scope.reuse_variables()\n", 
    "    logits_fake = discriminator(G_sample)\n", 
    "\n", 
    "# Get the list of variables for the discriminator and generator\n", 
    "D_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'discriminator')\n", 
    "G_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'generator') \n", 
    "\n", 
    "# get our solver\n", 
    "D_solver, G_solver = get_solvers()\n", 
    "\n", 
    "# get our loss\n", 
    "D_loss, G_loss = gan_loss(logits_real, logits_fake)\n", 
    "\n", 
    "# setup training steps\n", 
    "D_train_step = D_solver.minimize(D_loss, var_list=D_vars)\n", 
    "G_train_step = G_solver.minimize(G_loss, var_list=G_vars)\n", 
    "D_extra_step = tf.get_collection(tf.GraphKeys.UPDATE_OPS, 'discriminator')\n", 
    "G_extra_step = tf.get_collection(tf.GraphKeys.UPDATE_OPS, 'generator')"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "source": [
    "# Training a GAN!\n", 
    "Well that wasn't so hard, was it? After the first epoch, you should see fuzzy outlines, clear shapes as you approach epoch 3, and decent shapes, about half of which will be sharp and clearly recognizable as we pass epoch 5. In our case, we'll simply train D(x) and G(z) with one batch each every iteration. However, papers often experiment with different schedules of training D(x) and G(z), sometimes doing one for more steps than the other, or even training each one until the loss gets \"good enough\" and then switching to training the other. "
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# a giant helper function\n", 
    "def run_a_gan(sess, G_train_step, G_loss, D_train_step, D_loss, G_extra_step, D_extra_step,\\\n", 
    "              show_every=2, print_every=1, batch_size=128, num_epoch=10):\n", 
    "    \"\"\"Train a GAN for a certain number of epochs.\n", 
    "    \n", 
    "    Inputs:\n", 
    "    - sess: A tf.Session that we want to use to run our data\n", 
    "    - G_train_step: A training step for the Generator\n", 
    "    - G_loss: Generator loss\n", 
    "    - D_train_step: A training step for the Generator\n", 
    "    - D_loss: Discriminator loss\n", 
    "    - G_extra_step: A collection of tf.GraphKeys.UPDATE_OPS for generator\n", 
    "    - D_extra_step: A collection of tf.GraphKeys.UPDATE_OPS for discriminator\n", 
    "    Returns:\n", 
    "        Nothing\n", 
    "    \"\"\"\n", 
    "    # compute the number of iterations we need\n", 
    "    mnist = MNIST(batch_size=batch_size, shuffle=True)\n", 
    "    for epoch in range(num_epoch):\n", 
    "        # every show often, show a sample result\n", 
    "        if epoch % show_every == 0:\n", 
    "            samples = sess.run(G_sample)\n", 
    "            fig = show_images(samples[:16])\n", 
    "            plt.show()\n", 
    "            print()\n", 
    "        for (minibatch, minbatch_y) in mnist:\n", 
    "            # run a batch of data through the network\n", 
    "            _, D_loss_curr = sess.run([D_train_step, D_loss], feed_dict={x: minibatch})\n", 
    "            _, G_loss_curr = sess.run([G_train_step, G_loss])\n", 
    "\n", 
    "        # print loss every so often.\n", 
    "        # We want to make sure D_loss doesn't go to 0\n", 
    "        if epoch % print_every == 0:\n", 
    "            print('Epoch: {}, D: {:.4}, G:{:.4}'.format(epoch,D_loss_curr,G_loss_curr))\n", 
    "    print('Final images')\n", 
    "    samples = sess.run(G_sample)\n", 
    "\n", 
    "    fig = show_images(samples[:16])\n", 
    "    plt.show()"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "source": [
    "#### Train your GAN! This should take about 10 minutes on a CPU, or less than a minute on GPU."
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "with get_session() as sess:\n", 
    "    sess.run(tf.global_variables_initializer())\n", 
    "    run_a_gan(sess,G_train_step,G_loss,D_train_step,D_loss,G_extra_step,D_extra_step)"
   ], 
   "outputs": [], 
   "metadata": {
    "scrolled": true, 
    "collapsed": false
   }
  }, 
  {
   "source": [
    "# Least Squares GAN\n", 
    "We'll now look at [Least Squares GAN](https://arxiv.org/abs/1611.04076), a newer, more stable alternative to the original GAN loss function. For this part, all we have to do is change the loss function and retrain the model. We'll implement equation (9) in the paper, with the generator loss:\n", 
    "$$\\ell_G  =  \\frac{1}{2}\\mathbb{E}_{z \\sim p(z)}\\left[\\left(D(G(z))-1\\right)^2\\right]$$\n", 
    "and the discriminator loss:\n", 
    "$$ \\ell_D = \\frac{1}{2}\\mathbb{E}_{x \\sim p_\\text{data}}\\left[\\left(D(x)-1\\right)^2\\right] + \\frac{1}{2}\\mathbb{E}_{z \\sim p(z)}\\left[ \\left(D(G(z))\\right)^2\\right]$$\n", 
    "\n", 
    "\n", 
    "**HINTS**: Instead of computing the expectation, we will be averaging over elements of the minibatch, so make sure to combine the loss by averaging instead of summing. When plugging in for $D(x)$ and $D(G(z))$ use the direct output from the discriminator (`score_real` and `score_fake`)."
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def lsgan_loss(scores_real, scores_fake):\n", 
    "    \"\"\"Compute the Least Squares GAN loss.\n", 
    "    \n", 
    "    Inputs:\n", 
    "    - scores_real: Tensor, shape [batch_size, 1], output of discriminator\n", 
    "        The score for each real image\n", 
    "    - scores_fake: Tensor, shape[batch_size, 1], output of discriminator\n", 
    "        The score for each fake image    \n", 
    "          \n", 
    "    Returns:\n", 
    "    - D_loss: discriminator loss scalar\n", 
    "    - G_loss: generator loss scalar\n", 
    "    \"\"\"\n", 
    "    # TODO: compute D_loss and G_loss\n", 
    "    D_loss = None\n", 
    "    G_loss = None\n", 
    "    pass\n", 
    "    return D_loss, G_loss"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "source": [
    "Test your LSGAN loss. You should see errors less than 1e-7."
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def test_lsgan_loss(score_real, score_fake, d_loss_true, g_loss_true):\n", 
    "    with get_session() as sess:\n", 
    "        d_loss, g_loss = sess.run(\n", 
    "            lsgan_loss(tf.constant(score_real), tf.constant(score_fake)))\n", 
    "    print(\"Maximum error in d_loss: %g\"%rel_error(d_loss_true, d_loss))\n", 
    "    print(\"Maximum error in g_loss: %g\"%rel_error(g_loss_true, g_loss))\n", 
    "\n", 
    "test_lsgan_loss(answers['logits_real'], answers['logits_fake'],\n", 
    "                answers['d_loss_lsgan_true'], answers['g_loss_lsgan_true'])"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "Create new training steps so we instead minimize the LSGAN loss:"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "D_loss, G_loss = lsgan_loss(logits_real, logits_fake)\n", 
    "D_train_step = D_solver.minimize(D_loss, var_list=D_vars)\n", 
    "G_train_step = G_solver.minimize(G_loss, var_list=G_vars)"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "source": [
    "_Run the following cell to train your model!_"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "with get_session() as sess:\n", 
    "    sess.run(tf.global_variables_initializer())\n", 
    "    run_a_gan(sess, G_train_step, G_loss, D_train_step, D_loss, G_extra_step, D_extra_step)"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "# Deep Convolutional GANs\n", 
    "In the first part of the notebook, we implemented an almost direct copy of the original GAN network from Ian Goodfellow. However, this network architecture allows no real spatial reasoning. It is unable to reason about things like \"sharp edges\" in general because it lacks any convolutional layers. Thus, in this section, we will implement some of the ideas from [DCGAN](https://arxiv.org/abs/1511.06434), where we use convolutional networks as our discriminators and generators.\n", 
    "\n", 
    "#### Discriminator\n", 
    "We will use a discriminator inspired by the TensorFlow MNIST classification [tutorial](https://www.tensorflow.org/get_started/mnist/pros), which is able to get above 99% accuracy on the MNIST dataset fairly quickly. *Be sure to check the dimensions of x and reshape when needed*, fully connected blocks expect [N,D] Tensors while conv2d blocks expect [N,H,W,C] Tensors. Please use `tf.layers` to define the following architecture:\n", 
    "\n", 
    "Architecture:\n", 
    "* Conv2D: 32 Filters, 5x5, Stride 1, padding 0\n", 
    "* Leaky ReLU(alpha=0.01)\n", 
    "* Max Pool 2x2, Stride 2\n", 
    "* Conv2D: 64 Filters, 5x5, Stride 1, padding 0\n", 
    "* Leaky ReLU(alpha=0.01)\n", 
    "* Max Pool 2x2, Stride 2\n", 
    "* Flatten\n", 
    "* Fully Connected with output size 4 x 4 x 64\n", 
    "* Leaky ReLU(alpha=0.01)\n", 
    "* Fully Connected with output size 1\n", 
    "\n", 
    "Once again, please use biases for all convolutional and fully connected layers, and use the default parameter initializers. Note that a padding of 0 can be accomplished with the 'VALID' padding option."
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def discriminator(x):\n", 
    "    \"\"\"Compute discriminator score for a batch of input images.\n", 
    "    \n", 
    "    Inputs:\n", 
    "    - x: TensorFlow Tensor of flattened input images, shape [batch_size, 784]\n", 
    "    \n", 
    "    Returns:\n", 
    "    TensorFlow Tensor with shape [batch_size, 1], containing the score \n", 
    "    for an image being real for each input image.\n", 
    "    \"\"\"\n", 
    "    with tf.variable_scope(\"discriminator\"):\n", 
    "        # TODO: implement architecture\n", 
    "        pass\n", 
    "        return logits\n", 
    "test_discriminator(1102721)"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "#### Generator\n", 
    "For the generator, we will copy the architecture exactly from the [InfoGAN paper](https://arxiv.org/pdf/1606.03657.pdf). See Appendix C.1 MNIST. Please use `tf.layers` for your implementation. You might find the documentation for [tf.layers.conv2d_transpose](https://www.tensorflow.org/api_docs/python/tf/layers/conv2d_transpose) useful. The architecture is as follows.\n", 
    "\n", 
    "Architecture:\n", 
    "* Fully connected with output size 1024 \n", 
    "* `ReLU`\n", 
    "* BatchNorm\n", 
    "* Fully connected with output size 7 x 7 x 128 \n", 
    "* `ReLU`\n", 
    "* BatchNorm\n", 
    "* Resize into Image Tensor of size 7, 7, 128\n", 
    "* Conv2D^T (transpose): 64 filters of 4x4, stride 2\n", 
    "* `ReLU`\n", 
    "* BatchNorm\n", 
    "* Conv2d^T (transpose): 1 filter of 4x4, stride 2\n", 
    "* `TanH`\n", 
    "\n", 
    "Once again, use biases for the fully connected and transpose convolutional layers. Please use the default initializers for your parameters. For padding, choose the 'same' option for transpose convolutions. For Batch Normalization, assume we are always in 'training' mode."
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "def generator(z):\n", 
    "    \"\"\"Generate images from a random noise vector.\n", 
    "    \n", 
    "    Inputs:\n", 
    "    - z: TensorFlow Tensor of random noise with shape [batch_size, noise_dim]\n", 
    "    \n", 
    "    Returns:\n", 
    "    TensorFlow Tensor of generated images, with shape [batch_size, 784].\n", 
    "    \"\"\"\n", 
    "    with tf.variable_scope(\"generator\"):\n", 
    "        # TODO: implement architecture\n", 
    "        pass\n", 
    "        return img\n", 
    "test_generator(6595521)"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "We have to recreate our network since we've changed our functions."
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "tf.reset_default_graph()\n", 
    "\n", 
    "batch_size = 128\n", 
    "# our noise dimension\n", 
    "noise_dim = 96\n", 
    "\n", 
    "# placeholders for images from the training dataset\n", 
    "x = tf.placeholder(tf.float32, [None, 784])\n", 
    "z = sample_noise(batch_size, noise_dim)\n", 
    "# generated images\n", 
    "G_sample = generator(z)\n", 
    "\n", 
    "with tf.variable_scope(\"\") as scope:\n", 
    "    #scale images to be -1 to 1\n", 
    "    logits_real = discriminator(preprocess_img(x))\n", 
    "    # Re-use discriminator weights on new inputs\n", 
    "    scope.reuse_variables()\n", 
    "    logits_fake = discriminator(G_sample)\n", 
    "\n", 
    "# Get the list of variables for the discriminator and generator\n", 
    "D_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,'discriminator')\n", 
    "G_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,'generator') \n", 
    "\n", 
    "D_solver,G_solver = get_solvers()\n", 
    "D_loss, G_loss = gan_loss(logits_real, logits_fake)\n", 
    "D_train_step = D_solver.minimize(D_loss, var_list=D_vars)\n", 
    "G_train_step = G_solver.minimize(G_loss, var_list=G_vars)\n", 
    "D_extra_step = tf.get_collection(tf.GraphKeys.UPDATE_OPS,'discriminator')\n", 
    "G_extra_step = tf.get_collection(tf.GraphKeys.UPDATE_OPS,'generator')"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "source": [
    "### Train and evaluate a DCGAN\n", 
    "This is the one part of A3 that significantly benefits from using a GPU. It takes 3 minutes on a GPU for the requested five epochs. Or about 50 minutes on a dual core laptop on CPU (feel free to use 3 epochs if you do it on CPU)."
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "with get_session() as sess:\n", 
    "    sess.run(tf.global_variables_initializer())\n", 
    "    run_a_gan(sess,G_train_step,G_loss,D_train_step,D_loss,G_extra_step,D_extra_step,num_epoch=5)"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [], 
   "outputs": [], 
   "metadata": {
    "collapsed": true
   }
  }, 
  {
   "source": [
    "## INLINE QUESTION 1\n", 
    "\n", 
    "We will look at an example to see why alternating minimization of the same objective (like in a GAN) can be tricky business.\n", 
    "\n", 
    "Consider $f(x,y)=xy$. What does $\\min_x\\max_y f(x,y)$ evaluate to? (Hint: minmax tries to minimize the maximum value achievable.)\n", 
    "\n", 
    "Now try to evaluate this function numerically for 6 steps, starting at the point $(1,1)$, \n", 
    "by using alternating gradient (first updating y, then updating x) with step size $1$. \n", 
    "You'll find that writing out the update step in terms of $x_t,y_t,x_{t+1},y_{t+1}$ will be useful.\n", 
    "\n", 
    "Record the six pairs of explicit values for $(x_t,y_t)$ in the table below."
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "source": [
    "### Your answer:\n", 
    " \n", 
    " $y_0$ | $y_1$ | $y_2$ | $y_3$ | $y_4$ | $y_5$ | $y_6$ \n", 
    " ----- | ----- | ----- | ----- | ----- | ----- | ----- \n", 
    "   1   |       |       |       |       |       |       \n", 
    " $x_0$ | $x_1$ | $x_2$ | $x_3$ | $x_4$ | $x_5$ | $x_6$ \n", 
    "   1   |       |       |       |       |       |       \n", 
    "   "
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "source": [
    "## INLINE QUESTION 2\n", 
    "Using this method, will we ever reach the optimal value? Why or why not?"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "source": [
    "### Your answer:"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "source": [
    "## INLINE QUESTION 3\n", 
    "If the generator loss decreases during training while the discriminator loss stays at a constant high value from the start, is this a good sign? Why or why not? A qualitative answer is sufficient"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "source": [
    "### Your answer:"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }
 ], 
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3", 
   "name": "python3", 
   "language": "python"
  }, 
  "language_info": {
   "mimetype": "text/x-python", 
   "nbconvert_exporter": "python", 
   "name": "python", 
   "file_extension": ".py", 
   "version": "3.6.1", 
   "pygments_lexer": "ipython3", 
   "codemirror_mode": {
    "version": 3, 
    "name": "ipython"
   }
  }
 }
}